const webpack = require('webpack');

const path = require('path');
const glob = require('glob-all');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const PurgecssPlugin = require('purgecss-webpack-plugin');

const isProd = process.env.NODE_ENV === 'production';

module.exports = {
	productionSourceMap: false,

	configureWebpack: (config) => {
		const plugins = [];

		plugins.push(
			new webpack.DefinePlugin({
				// 在客户端包中将hotRequire替换成require
				hotRequire: 'require',
				// 在客户端包中将hotRequireContext替换成require.context（必须替换，不能只替换hotRequire）
				'hotRequire.context': 'require.context'
			})
		);

		if (isProd) {
			plugins.push(
				new UglifyJsPlugin({
					uglifyOptions: {
						compress: {
							warnings: false,
							drop_console: true,
							drop_debugger: true,
							pure_funcs: ['console.log', 'console.debug'] //移除console
						}
					}
				})
			);

			plugins.push(
				new PurgecssPlugin({
					paths: glob.sync([path.join(__dirname, './**/*.vue')]),
					extractors: [
						{
							extractor: class Extractor {
								static extract(content) {
									const validSection = content.replace(/<style([\s\S]*?)<\/style>+/gim, '');
									return validSection.match(/[A-Za-z0-9-_:/]+/g) || [];
								}
							},
							extensions: ['html', 'vue']
						}
					],
					whitelist: ['html', 'body'],
					whitelistPatterns: [/el-.*/],
					whitelistPatternsChildren: [/^token/, /^pre/, /^code/]
				})
			);
		}

		config.plugins = [...config.plugins, ...plugins];
	}
};
